<template>
  <div class="add-role">
    <el-form :model="form">
      <el-form-item label="角色名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="角色编码">
        <el-input v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
    </el-form>
    <el-form>
      <el-button @click="$emit('cancel')">取 消</el-button>
      <el-button type="primary" @click="addOrUpdate">确 定</el-button>
    </el-form>
  </div>
</template>

<script>
import { addRole, getRoleById } from '@/services/role'

export default {
  name: 'addRole',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      form: {
        code: '',
        name: '',
        description: ''
      }
    }
  },
  created () {
    // 有限制
    if (this.isEdit === false) {
      this.form = {}
    } else {
      this.getRoleByIdList()
    }
  },
  methods: {
    async getRoleByIdList () {
      const { data } = await getRoleById(this.roleId)
      if (data.code === '000000') {
        this.form = data.data
      }
    },
    async addOrUpdate () {
      for (const k in this.form) {
        if (this.form[k] === '') {
          return this.$message.error('数据填写不全')
        }
      }
      const { data } = await addRole(this.form)
      if (data.code === '000000') {
        this.$message.success('添加成功')
        this.$emit('success', false)
        this.form = {}
      } else {
        this.$message.error('添加失败')
        this.$emit('ishide', false)
      }
    }
  },
  watch: {
    isEdit () {
      if (this.isEdit === false) {
        this.form = {}
      } else {
        this.getRoleByIdList()
      }
    }
  }
}
</script>

<style>
</style>
